package com.tongcheng.edu.config;

import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;


//@Profile({"!prod"})
@Configuration
@EnableSwagger2
public class SpringFoxConfiguration {

    @Bean
    public Docket imscApiV1Docket() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> paramList = Lists.newArrayList();
        tokenPar.name("X-Access-Token")
                .description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        paramList.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(apiKeys())
                .securityContexts(newArrayList(securityContext()))
                .select()
                .paths(PathSelectors.regex(".*"))
                .paths(PathSelectors.regex("/edu"+"/.*"))
                .build()
                .globalOperationParameters(paramList)
                .groupName("api-v1");
    }


    private List<ApiKey> apiKeys() {
        return newArrayList(
                new ApiKey("X-Access-Token", "X-Access-Token", "header"),
                new ApiKey("X-Operation-Token", "X-Operation-Token", "header")
        );
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(path -> !PathSelectors.regex("/security/.*").apply(path))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(
                new SecurityReference("X-Access-Token", authorizationScopes)
               );
    }

}
